using System;
using FytSoa.Common.Utils;
using FytSoa.Domain.Core.Result;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace FytSoa.ApiService.Filters
{
    /// <summary>
    /// 结果过滤器
    /// </summary>
    public class AopResultFilter : IResourceFilter
    {
        public void OnResourceExecuting(ResourceExecutingContext context)
        {
            var obj = context.Result;
            if (obj?.GetType() != typeof(ObjectResult)) return;
            try
            {
                var result = (ObjectResult)obj;
                if (!(result.Value.GetType().Name.Contains(typeof(ApiResult<>).Name)|| result.Value.GetType().Name.Contains(typeof(ApiResult<>).Name)))
                {
                    context.Result= new JsonResult(JResult<object>.Success(result.Value));
                }
            }
            catch (Exception ex)
            {
                context.Result = obj;
                Logger.Error(ex);
                throw;
            }
        }

        public void OnResourceExecuted(ResourceExecutedContext context)
        {
            throw new NotImplementedException();
        }
    }
}